﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using Microsoft.Ajax.Utilities;
using PagedList;

namespace CubicFWNet.Mvc.Controllers
{
    public class CustomerServiceController : ControllerBase
    {
        private OrderApp _orderApp;
        private CustomerApp _customerApp;
        private InvoiceApp _invoiceApp;
        private ProductApp _productApp;
        private FinanceInvoiceApp _financeInvoiceApp;
        private OperateRecordApp _operateRecordApp;
        private ArapApp _arapApp;
        private OrderProductApp _orderProductApp;
        public CustomerServiceController()
        {
            _orderApp = new OrderApp();
            _customerApp = new CustomerApp();
            _invoiceApp = new InvoiceApp();
            _productApp = new ProductApp();
            _financeInvoiceApp = new FinanceInvoiceApp();
            _operateRecordApp = new OperateRecordApp();
            _arapApp = new ArapApp();
            _orderProductApp = new OrderProductApp();
        }

        // GET: CustomerService
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult InvoiceQuery(int page = 1, string number = "", string takeCompany = "")
        {
            ViewBag.Number = number.Trim();
            ViewBag.TakeCompany = takeCompany.Trim();

            IPagedList<InvoiceView> tecjList = _invoiceApp.GetInvoiceListGroupByOrder(number.Trim()).ToPagedList(page, 10);
            return View(tecjList);
        }
        /// <summary>
        /// 相同订单下所有发货单汇总页面
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ActionResult InvoiceCompose(Guid orderId)
        {
            JsonDeliveryProducts jsondp = new JsonDeliveryProducts();
            List<ProductTechnologyView> proListBack = new List<ProductTechnologyView>();
            List<Guid> guid = new List<Guid>();
            IQueryable<ProductTechnologyView> proList = _productApp.GetProductListByOrderId(orderId);//该订单包涵所有产品集合数据
            foreach (var item in proList)
            {
                if (guid.Contains(item.ProductId))
                {
                    var obj = proListBack.FirstOrDefault(a => a.ProductId == item.ProductId);
                    if (obj != null)
                    {
                        obj.Amount = obj.Amount + item.Amount;
                    }
                }
                else
                {
                    proListBack.Add(item);
                    guid.Add(item.ProductId);
                }
            }


            List<Invoice> invoiceList = _invoiceApp.GetInvoiceListByOrderId(orderId).ToList();//该订单下所有发货单数据
            Order order = _orderApp.GetInfo(orderId);
            Customer customer = _customerApp.GetInfo(order.CustomeId.Value);
            User xiaoshou = _customerApp.GetUser(order.CreatorId.Value);

            
            IQueryable<FinanceInvoice> fiList = _financeInvoiceApp.GetFinanceInvoiceListByoId(orderId);//财务开票的数据
            List<DeliveryProduct> invoiceListTotal = new List<DeliveryProduct>();//总产品集合
            List<DeliveryProduct> fiListTotal = new List<DeliveryProduct>();//已开发票的产品集合

            foreach (var item in invoiceList)
            {
                List<DeliveryProduct> itemList = Common.Json.ToObject<List<DeliveryProduct>>(item.Data);
                invoiceListTotal = invoiceListTotal.Concat(itemList).ToList();
            }
            foreach (var item in fiList)
            {
                List<DeliveryProduct> itemList = Common.Json.ToObject<List<DeliveryProduct>>(item.ProductData);
                fiListTotal = fiListTotal.Concat(itemList).ToList();
            }
            List<DeliveryProduct> invoiceListDistinct = invoiceListTotal.DistinctBy(a => a.ProductId).ToList();
            //与原订单相比
            foreach (var item in proListBack)
            {
                decimal amountA = invoiceListTotal.Where(a => a.ProductId == item.ProductId).Sum(a => a.ProductAmount);
                item.Amount = item.Amount - amountA;
                //item.Price = item.ProductAmount * item.ProductPrice * item.ProductTax;
            }
            //于已开票的订单相比
            foreach (var item in invoiceListDistinct)
            {
                //decimal tax = Convert.ToDecimal(1.17);//增值税
                decimal amountA = invoiceListTotal.Where(a => a.ProductId == item.ProductId).Sum(a => a.ProductAmount);
                decimal amountB = fiListTotal.Where(a => a.ProductId == item.ProductId).Sum(a => a.ProductAmount);
                item.ProductAmount = amountA - amountB;
                item.TotalMoney = item.ProductAmount * item.ProductPrice * item.ProductTax;
            }

            ViewBag.Customer = customer;
            ViewBag.Xiaoshou = xiaoshou;
            ViewBag.InvoiceListDistinct = invoiceListDistinct;//剩余为开发票的产品数量
            ViewBag.InvoiceList = invoiceList;
            ViewBag.ProList = proListBack;
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(order);
        }

        public ActionResult InvoiceInfoAccount(Guid inId)
        {
            Invoice invoice = _invoiceApp.GetSingleInvoice(inId);
            Order order = _orderApp.GetInfo(invoice.OrderId);
            Customer customer = _customerApp.GetInfo(order.CustomeId.Value);
            InvoceType invoceType = _invoiceApp.GetSingleInvoceType(invoice.Type);
            SendCar sc = _invoiceApp.GetSingleSendCar(invoice.Id);
            ExpressOrder exp = _invoiceApp.GetSingleExpressOrder(invoice.Id);

            //对账完成
            InvoiceOther io = _invoiceApp.GetSingleInvoiceOther(invoice.Id, 1);
            ViewBag.InvoiceOther1 = io;

            //寄送完成
            InvoiceOther ioo = _invoiceApp.GetSingleInvoiceOther(invoice.Id, 2);
            ViewBag.InvoiceOther2 = ioo;

            ViewBag.InvoceTypeName = invoceType == null ? "" : invoceType.TypeName; ;
            ViewBag.CustomerShortName = customer.ShortName;
            ViewBag.Invoice = invoice;
            ViewBag.SendCar = sc;
            ViewBag.ExpressOrder = exp;
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(order);
        }


        public ActionResult YingshouQuery(int page = 1, string financeNumber = "", string customerName = "")
        {
            ViewBag.FinanceNumber = financeNumber.Trim();
            ViewBag.CustomerName = customerName.Trim();

            IPagedList<ArapView> arapList = _arapApp.GetListArapViews(1, -10, financeNumber.Trim(), customerName.Trim()).ToPagedList(page, 10);
            return View(arapList);
        }
        public ActionResult YingshouInfo(Guid id)
        {
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            Arap arap = _arapApp.GetSingle(id);
            FinanceInvoice financeInvoice = null;
            Order order = null;
            Customer customer = null;
            decimal amount = 0;

            if (arap != null)
            {
                financeInvoice = _financeInvoiceApp.GetSingleFinanceInvoice(arap.FinanceInvoiceId);
                order = _orderApp.GetInfo(arap.OrderId);
                if (order != null && order.CustomeId != null)
                {
                    customer = _customerApp.GetInfo(order.CustomeId.Value);
                    if (financeInvoice != null)
                    {
                        List<DeliveryProduct> itemList = Common.Json.ToObject<List<DeliveryProduct>>(financeInvoice.ProductData);
                        foreach (var item in itemList)
                        {
                            amount += item.TotalMoney;
                        }
                    }
                    if (arap.Status == 1)
                    {
                        ViewBag.OperationName = arap.CreatorName;//操作人
                        ViewBag.OperationTime = arap.CreateTime.Value.ToString("yyyy-MM-dd");//操作时间
                    }
                }
            }

            ViewBag.FinanceInvoice = financeInvoice;
            ViewBag.Customer = customer;
            ViewBag.Order = order;
            ViewBag.Amount = amount;

            return View(arap);
        }



        public ActionResult SendTicketQuery(int page = 1, string number = "", string takeCompany = "")
        {
            ViewBag.Number = number.Trim();
            ViewBag.TakeCompany = takeCompany.Trim();

            IPagedList<InvoiceView> tecjList = _financeInvoiceApp.GetFinanceInvoicesList(1, number.Trim()).ToPagedList(page, 10);
            return View(tecjList);
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateInvoice(Guid id, int type, InvoiceOther web)
        {
            DateTime nowTime = DateTime.Now;
            Guid newId = Guid.NewGuid();
            web.Id = newId;
            web.Type = type;
            web.InvoicId = id;
            web.CreatorId = operatorModel.UserId;
            web.CreatorName = operatorModel.FamilyName;
            web.CreateTime = nowTime;
            _invoiceApp.AddInvoiceOther(web);

            //对账
            if (type == 1)
            {
                Invoice i = _invoiceApp.GetSingleInvoice(id);
                i.Status = 3;
                _invoiceApp.Update(i);//修改发货单状态
            }
            //寄送
            if (type == 2)
            {
                Invoice i = _invoiceApp.GetSingleInvoice(id);
                i.Status = 4;
                _invoiceApp.Update(i);//修改发货单状态
            }

            return Result.ToJson();
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateInvoiceCompose(FinanceInvoice web)
        {
            if (web.Type == 0)
            {
                DateTime nowTime = DateTime.Now;
                Guid newId = Guid.NewGuid();
                web.Id = newId;
                web.ApplyTime = nowTime;
                web.ApplyId = operatorModel.UserId;
                web.Status = -1;
                _financeInvoiceApp.Add(web);//插入财务对账表(开发票)

                //插入给下一个工作人员添加人工记录
                OperateRecord o1 = new OperateRecord();
                o1.Id = Guid.NewGuid();
                o1.ItemId = newId;
                o1.TypeId = 27;
                o1.StartTime = nowTime;
                o1.EndTime = null;
                o1.CreatorId = null;
                _operateRecordApp.AddOperateRecord(o1);
            }
            if (web.Type == 1)
            {
                DateTime nowTime = DateTime.Now;
                Guid newId = Guid.NewGuid();
                web.Id = newId;
                web.ApplyTime = nowTime;
                web.ApplyId = operatorModel.UserId;
                web.Status = 2;

                if (!string.IsNullOrEmpty(web.ProductData))
                {
                    List<DeliveryProduct> itemList = Common.Json.ToObject<List<DeliveryProduct>>(web.ProductData);
                    foreach (var item in itemList)
                    {
                        item.StrCreateTime = nowTime.ToString("yyyy-MM-dd");
                        item.StrEndTime = "";
                    }
                    web.ProductData = itemList.ToJson();
                }
                _financeInvoiceApp.Add(web);//插入财务对账表(开发票)

                //插入应收应付表
                Arap arap = new Arap();
                Guid newGuid = Guid.NewGuid();
                arap.Id = newGuid;
                arap.Status = -1;
                arap.FinanceInvoiceId = web.Id;
                arap.OrderId = web.OrderId;
                arap.ApplyTime = nowTime;
                arap.FinanceNumber = "无票号";
                arap.Type = 1;
                arap.InvoiceType = 1;
                arap.TotalMoney = web.TotalMoney;
                _arapApp.Add(arap);

                OperateRecord o1 = new OperateRecord();
                o1.Id = Guid.NewGuid();
                o1.ItemId = newGuid;
                o1.TypeId = 25;
                o1.StartTime = nowTime;
                o1.EndTime = null;
                o1.CreatorId = null;
                _operateRecordApp.AddOperateRecord(o1);
            }

            return Result.ToJson();
        }

        /// <summary>
        /// 订单查询[填写发货单]
        /// </summary>
        /// <returns></returns>
        public ActionResult Orders(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end.AddDays(1), 3, 0, name, "", number).ToPagedList(page, 10);
            return View(orderList);
        }

        /// <summary>
        /// 完成订单
        /// </summary>
        /// <returns></returns>
        public ActionResult FinishOrder()
        {
            string str = Request.QueryString["OID"];
            OrderInfo order = new OrderInfo();
            List<ProductView> opList = new List<ProductView>();
            if (str != null)
            {
                Guid oID = new Guid(str);
                order = _orderApp.GetFullInfo(oID);
                if (order != null)
                {
                    opList = _orderProductApp.GetListByOrderID(oID).ToList();
                }
            }

            ViewBag.Order = order;
            ViewBag.OpList = opList;
            return View();
        }


        /// <summary>
        /// 完成订单{提交数据}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FinishOrder(FormCollection fc)
        {
            Guid oID = new Guid(fc["OID"]);
            Order order = _orderApp.GetInfo(oID);

            order.Stage = 10;
            order.Memo = fc["Memo"];
            order.EndTime = DateTime.Now;
            _orderApp.Update(order);
            return RedirectToAction("OrderFinish", "CustomerService");
        }


        /// <summary>
        /// 订单查询[已完成]
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderFinish(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end.AddDays(1), 10, 0, name, "", number).ToPagedList(page, 10);
            return View(orderList);
        }

    }
}